package com.jialiang.yojcodesandbox.service.impl.java;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.jialiang.yojcodesandbox.model.ExecuteMessage;
import com.jialiang.yojcodesandbox.service.impl.JavaCodeSandboxTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 基于 Java 代码沙箱模板方法的 Docker 代码沙箱实现
 * 只需要重写 runFile 方法，其他方法复用模板方法里的
 * todo docker代码沙箱待完善
 */
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate {

    // 超时时间
    private static final long TIME_OUT = 5000L;

    // 默认完成初始化
    private static final Boolean FIRST_INIT = true;

    /**
     * 3.创建容器，把文件复制到容器内
     * @param userCodeFile 用户代码文件
     * @param inputList    输入列表
     * @return
     */
    @Override
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        // 存放用户代码文件的父目录
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        // 获取默认的Docker Client，与Docker守护进程交互
        DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://118.31.105.128:2375").build();

        // 1) 拉取镜像
        // Docker不会拉取重复镜像
        String image = "openjdk:8-alpine";
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            // 回调函数：拉取镜像后自动执行
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        // 等待完成拉取镜像后，调用回调函数，异步变同步
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                e.printStackTrace();
            }
        }
        System.out.println("下载完成");

        // 2) 创建容器，设置容器配置
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        // 宿主机配置
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L); // 限制内存为100M
        hostConfig.withMemorySwap(0L);  // 限制内存交换
        hostConfig.withCpuCount(1L);    // 限制CPU个数为1
        String profileConfig = ResourceUtil.readUtf8Str("profile.json");
        hostConfig.withSecurityOpts(Arrays.asList("seccomp=" + profileConfig)); // 安全管理配置字符串
        // 创建容器时指定文件路径映射
        // 同步本地文件到容器中，是服务器上数据卷位置，不是windows本地目录
        hostConfig.setBinds(new Bind("/data/yoj-app", new Volume("/app"))); // 数据卷映射
        // hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/data/volume/yoj-docker")));
        CreateContainerResponse createContainerResponse = containerCmd
                // .withName(containerName) // 设置容器名
                .withHostConfig(hostConfig)
                // 将docker容器和本地终端进行连接，在终端获取输入、输出
                .withNetworkDisabled(true) // 关闭网络
                .withReadonlyRootfs(true) // 禁止往根目录写文件
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(true) // 交互终端
                .exec();
        System.out.println(createContainerResponse);
        String containerId = createContainerResponse.getId();

        // 3) 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // 4) 执行命令并获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();

        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            // Docker容器执行命令：docker exec keen_blackwell java -cp /app Main 1 3
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    // 从命令行终端获取输出
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .withAttachStderr(true)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time = 0L;
            // 判断是否超时
            final boolean[] timeout = {true};
            // 占用最大内存
            final Long[] maxMemory = {0L};

            // 获取占用内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            // 回调函数：监听容器统计信息（内存...）
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    Long memory = statistics.getMemoryStats().getUsage();
                    System.out.println("内存占用：" + memory);
                    maxMemory[0] = Math.max(maxMemory[0], memory);
                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });
            statsCmd.exec(statisticsResultCallback);

            String execId = execCreateCmdResponse.getId();
            // 回调函数：容器执行命令后自动执行，获取执行结果
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    // 如果执行完成，则表示没超时
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    // 执行错误，获取错误结果
                    if (streamType.STDERR.equals(streamType)) {
                        // 内部类要使用外部变量，这个变量必须是final
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        // 执行正确，获取结果
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            // 执行接收的是【异步回调】
            // 程序输出很多值，处理需要耗时，防止超时操作需要回调
            try {
                // 统计程序执行时间
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MINUTES); // 阻塞等待程序完成后获取结果
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                e.printStackTrace();
            }

            // 设置程序执行信息
            executeMessage.setOutput(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }

}